﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text;
using System.Web.Caching;
using NLog;
using Aandelendelen.String;
using Aandelendelen.Caching;

namespace Aandelendelen.Mail
{
	public class PostScriptumCollection : Collection<PostScriptum>, ICacheable
	{
		public static string CacheName = "postscriptums"; 

		private static Logger logger = LogManager.GetCurrentClassLogger();

		private PostScriptum currentPostScriptum = null;
		private Random random;

		public PostScriptumCollection()
			: base()
		{
			this.InitCacheKey();

			this.random = new Random();
			this.ReadPostScriptums();
		}

		private void ReadPostScriptums()
		{
			string path = HttpContext.Current.Server.MapPath("/App_Data/Mail.xml");
			XmlDocument doc = new XmlDocument();
			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/aandelendelen/postscriptum");

			foreach (XmlNode node in nodes)
			{
				this.Add(this.ReadPostScriptum(node));
			}

			doc.RemoveAll();
		}

		private PostScriptum ReadPostScriptum(XmlNode node)
		{
			XmlAttribute attr = node.Attributes["id"];
			int id = XmlConvert.ToInt32(attr.Value);

			attr = node.Attributes["probability"];
			double prob = XmlConvert.ToDouble(attr.Value);

			return new PostScriptum(id, node.InnerXml.Clean(), prob);
		}

		public PostScriptum FindID(int id)
		{
			if (this.currentPostScriptum.Id == id)
				return this.currentPostScriptum;

			foreach (PostScriptum ps in this)
				if (ps.Id == id)
					return ps;

			return null;
		}

		protected override void InsertItem(int index, PostScriptum item)
		{
			if (this.currentPostScriptum == null || item.Id > this.currentPostScriptum.Id)
				this.currentPostScriptum = item;

			base.InsertItem(index, item);
		}

		public PostScriptum CurrentPostScriptum
		{
			get { return this.currentPostScriptum; }
		}

		public double RandomValue
		{
			get
			{
				return this.random.NextDouble();
			}
		}

		public static PostScriptumCollection GetInstance()
		{
			return DataCache.GetCacheableObject<PostScriptumCollection>(CacheName);
		}

		public static PostScriptumCollection GetInstance(string cacheKey)
		{
			return DataCache.GetCacheableObject<PostScriptumCollection>(cacheKey);
		}

		#region ICacheable
		public CacheKey CacheKey { get; set; }

		public void CacheThis(string cacheKey)
		{
			this.CacheKey.CacheThis(cacheKey);
		}

		public void InitCacheKey()
		{
			CacheKey = new CacheKey()
			{
				CacheDependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/Mail.xml")),
				ObjectToCache = this
			};
		}
		#endregion


	}
}